// This code was written by Mike Gold  .  This code may be used only for educational purposes.
// Any distribution of this code may only be carried out with written consent from the author.
// Copyright ? 2006 by Microgold Software Inc. 

 



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Mime;


    public partial class SlideShowControl : KillCircularReference 
    {
        private const string NO_IMAGE_RIGHT_NOW = "nocover.jpg";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                ImageDirectory = ConfigurationManager.AppSettings["CoverImageDirectory"];

                if (Session["CurrentImageIndex"] == null)
                {
                    IndexImages();
                    DrawImage();
                }
                
                // the the initial URL
                imgCurrent.ImageUrl = GetImageUrl();                
            }
        }

        private void IndexImages()
        {

            // determine the actual path of the asp.net application on the server
            string fullSitePath = this.Request.PhysicalApplicationPath;

            // extend the path to include our slide show control image directory
            string serverImageDirectory = Server.MapPath(ImageDirectory);

            // save the path information in the Session State
            Session["FullImagePath"] = serverImageDirectory;

            // get all the files in the images directory with the desired extension
            string[] files = Directory.GetFiles(serverImageDirectory, String.Format("*.{0}", _imageExtension));

            // store all the file names in the session state, keyed by
            // the directory name and a unique integer.
            int count = 0;
            Session["CurrentImageIndex"] = 0;
            Session["ImageDirectory"] = ImageDirectory;
            string ImageIndexSessionKey = ImageDirectory + count.ToString();
            Session[ImageIndexSessionKey] = NO_IMAGE_RIGHT_NOW;
            foreach (string file in files)
            {
                ImageIndexSessionKey = ImageDirectory + count.ToString();
                Session[ImageIndexSessionKey] = file.Substring(file.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
                count++;
            }

            // store the number of images in the session state
            Session["ImageCount"] = count;

        }

        private string _imageExtension = "jpg";

        public string ImageExtension
        {
            get { return _imageExtension; }
            set { _imageExtension = value; }
        }

        private string _currentImage;

        public string CurrentImage
        {
            get { return _currentImage; }
            set { _currentImage = value; }
        }

        private string _currentImageIndex;

        public string CurrentImageIndex
        {
            get { return _currentImageIndex; }
            set { _currentImageIndex = value; }
        }

        private string _imageDirectory = @"images";

        public string ImageDirectory
        {
            get { return _imageDirectory; }
            set { _imageDirectory = value; }
        }

        public void Previous_Click(object sender, EventArgs e)
        {
            // go to the next image
            DecrementCurrentImageIndex();
            DrawImage();
        }

        public void Next_Click(object sender, EventArgs e)
        {
            IncrementCurrentImageIndex();
            DrawImage();
        }

        // public ContentType ImageType = new ContentType("jpeg");

        public void DrawImage()
        {
            // assign the image url using the current file name
            imgCurrent.ImageUrl = GetImageUrl();

            // also assign the correct dimensions for the image
            Size imageDimensions = GetImageDimensions();
            imgCurrent.Width = new Unit(imageDimensions.Width);
            imgCurrent.Height = new Unit(imageDimensions.Height);

            // redirect back to the controls containing page
            string urlName = this.Request.Url.ToString();
            this.Response.Redirect(urlName, true);
            //return;

            // ***********  Alternative way to show dynamic images ********
            // imgCurrent.ImageUrl = GetCurrentFileName().ToString();
            Bitmap bmpImageFrame = new Bitmap((int)imgCurrent.Width.Value, (int)imgCurrent.Height.Value);
            // retrieve the picture from the file on the server

            // get a graphics object from the image
            Graphics g = Graphics.FromImage(bmpImageFrame);
            g.Clear(Color.White); // clear the drawing surface
            string filename = GetCurrentFileName().ToString();
            Bitmap bmp = new Bitmap(filename);
            g.DrawImage(bmp, new Point(0, 0));

            string oldContent = Response.ContentType;
            Response.ContentType = "Image/jpeg";
            bmpImageFrame.Save(Response.OutputStream, ImageFormat.Jpeg);
            // save to the web data stream so the client can see it

            // clean up the bitmap memory
            bmpImageFrame.Dispose();
            bmp.Dispose();
        }

        private string GetImageUrl()
        {
            return this.Page.ResolveUrl(ImageDirectory + "/" + GetCurrentFileName().ToString());
        }

        /// <summary>
        /// Gets the image Width and Height from the actual bitmap
        /// </summary>
        /// <returns>size containing He</returns>
        private Size GetImageDimensions()
        {
            // get the image path for the current file
            string currentImagePath = Session["FullImagePath"] + "\\" + GetCurrentFileName();

            if (!File.Exists(currentImagePath))
            {
                return new Size(100, 100);
            }

            // put it in a bitmap
            Bitmap bmp = new Bitmap(currentImagePath);

            // use the bitmap class to get the dimensions of the bitmap
            Size result = new Size(bmp.Width, bmp.Height);

            // clean up the memory
            bmp.Dispose();

            // return the dimensions
            return result;
        }

        public void IncrementCurrentImageIndex()
        {
            // previous button automatically enabled when next button pressed
            Session["PreviousButtonEnabled"] = true;

            // if we have not reached the last picture, 
            // increment the current image index in the session
            if (((int)Session["CurrentImageIndex"]) < ((int)Session["ImageCount"] - 1))
            {
                Session["CurrentImageIndex"] = (int)Session["CurrentImageIndex"] + 1;
            }

            // Set the next button enabled state based
            // upon the current image index
            Session["NextButtonEnabled"] = ((int)Session["CurrentImageIndex"] < ((int)Session["ImageCount"] - 1));
        }

        public void DecrementCurrentImageIndex()
        {
            Session["NextButtonEnabled"] = true;

            if (((int)Session["CurrentImageIndex"]) >  0)
            {
                Session["CurrentImageIndex"] = (int)Session["CurrentImageIndex"] - 1;
            }

            Session["PreviousButtonEnabled"] = ((int)Session["CurrentImageIndex"]) > 0;
        }

        private object GetCurrentFileName()
        {
            if (Session["ImageDirectory"] == null)
            {
                return "";
            }

            return Session[Session["ImageDirectory"].ToString() + Session["CurrentImageIndex"].ToString()];
        }
    }
